package cn.xorange.commons.core.auth.handler;

import cn.xorange.commons.core.auth.mapper.UserPermissionMapper;
import cn.xorange.commons.security.configuration.SecurityProperties;
import cn.xorange.commons.security.constants.MenuConstants;
import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.security.entity.SecurityMenu;
import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.entity.vo.RouterVo;
import cn.xorange.commons.security.entity.vo.MetaVo;
import cn.xorange.commons.security.filter.FilterHandler;
import cn.xorange.commons.security.filter.LoginFilterService;
import cn.xorange.commons.security.service.SecurityService;
import cn.xorange.commons.core.constants.SysConstants;
import cn.xorange.commons.utils.http.ServletUtils;
import cn.xorange.commons.utils.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author : yangjian
 * @date : 2023/12/22
 */
public class FilterMenuHandler implements FilterHandler {

    @Resource
    SecurityProperties securityProperties;
    @Autowired
    UserPermissionMapper mapper;
    @Resource
    SecurityService  securityService;
    @Resource
    LoginFilterService loginFilterService;

    @Override
    public String url() {
        return SecurityConstants.URL_ROUTERS;
    }

    @Override
    public Boolean passToken() {
        return false;
    }

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response) {
        SecurityUser user = securityService.getLoginUser();

        List<SecurityMenu> menus;
        String superUser = loginFilterService.checkSuperUserLogin(user.getStaffId());
        if (SysConstants.FLAG_YES.equals(superUser)){
            menus = this.mapper.selectSuperMenu();
        }else {
            if(securityProperties.isEnableTenant() && Objects.isNull(user.getTenantId())){
                   user.setTenantId(SecurityConstants.DEFAULT_TENANT_ID);
            }
            menus = this.mapper.selectRouterMenu(user.getTenantId(), user.getUserId(),user.getIsAdmin());
        }

        List<SecurityMenu> menuTree = this.getChildPerms(menus, 0);

        ArrayList<RouterVo> routers = this.buildMenus(menuTree);
        ServletUtils.responseSuccessOut(response, routers);
    }

    public List<SecurityMenu> getChildPerms(List<SecurityMenu> list, int parentId)
    {
        List<SecurityMenu> returnList = new ArrayList<>();
        for (Iterator<SecurityMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SecurityMenu t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<SecurityMenu> list, SecurityMenu t)
    {
        // 得到子节点列表
        List<SecurityMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SecurityMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SecurityMenu> getChildList(List<SecurityMenu> list, SecurityMenu t)
    {
        List<SecurityMenu> tlist = new ArrayList<>();
        Iterator<SecurityMenu> it = list.iterator();
        while (it.hasNext())
        {
            SecurityMenu n = it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SecurityMenu> list, SecurityMenu t)
    {
        return !getChildList(list, t).isEmpty();
    }



    private ArrayList<RouterVo> buildMenus(List<SecurityMenu> menus){
        ArrayList<RouterVo> routers = new ArrayList<>();
        for (SecurityMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SecurityMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && MenuConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.upperFirst(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId() == 0 && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(MenuConstants.INNER_LINK);
                children.setName(StringUtils.upperFirst(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }



    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isMenuFrame(SecurityMenu menu) {
        return menu.getParentId() == 0 && MenuConstants.TYPE_MENU.equals(menu.getMenuType())
                && MenuConstants.NO_FRAME.equals(menu.getIsFrame());
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isInnerLink(SecurityMenu menu) {
        return MenuConstants.NO_FRAME.equals(menu.getIsFrame()) && ServletUtils.isHttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isParentView(SecurityMenu menu) {
        return menu.getParentId()!= 0 && MenuConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    private String getComponent(SecurityMenu menu) {
        String component = MenuConstants.LAYOUT;
        if (!StringUtils.isEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId() != 0 && isInnerLink(menu)) {
            component = MenuConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = MenuConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    private String getRouteName(SecurityMenu menu)
    {
        String routerName = StringUtils.upperFirst(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = "";
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    private String getRouterPath(SecurityMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if ( menu.getParentId() == 0 && MenuConstants.TYPE_DIR.equals(menu.getMenuType())
                && MenuConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    private String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[] { SysConstants.HTTP, SysConstants.HTTPS, SysConstants.WWW, ".", ":" },
                new String[] { "", "", "", "/", "/" });
    }
}
